package com.shuqi.activity;

import java.lang.reflect.Field;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.provider.Settings;
import android.provider.Settings.SettingNotFoundException;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.shuqi.activity.viewport.BookContentBottomView;
import com.shuqi.activity.viewport.BookContentMenuView;
import com.shuqi.activity.viewport.BookContentView;
import com.shuqi.activity.viewport.BottomDialog;
import com.shuqi.activity.viewport.CataLogLayout;
import com.shuqi.activity.viewport.CataLogLayout.onViewChangeListener;
import com.shuqi.activity.viewport.OrderDialog;
import com.shuqi.activity.viewport.OrderDialog.OnOrderDialogListener;
import com.shuqi.application.CataLogCache;
import com.shuqi.application.ShuqiApplication;
import com.shuqi.bookcontent.BookContentRender;
import com.shuqi.common.CheckUser;
import com.shuqi.common.ConfigVersion;
import com.shuqi.common.Constant;
import com.shuqi.common.PayTheme;
import com.shuqi.common.Urls;
import com.shuqi.common.utils.BookContentUtils;
import com.shuqi.common.utils.Log4an;
import com.shuqi.common.utils.SharedPreferenceUtil;
import com.shuqi.common.utils.ToastUtil;
import com.shuqi.common.utils.Util;
import com.shuqi.controller.R;
import com.shuqi.database.dao.impl.BookCataLogDao;
import com.shuqi.database.model.UserInfo;
import com.shuqi.interfaces.CheckUserListener;
import com.shuqi.model.BookContentModel;
import com.shuqi.model.BookContentModel.BookContentModelStatusListener;
import com.shuqi.model.BookContentSettings;
import com.shuqi.model.BookContentSettings.OnSettingListener;
import com.shuqi.model.bean.BookContentInfo;
import com.shuqi.model.bean.ChapterInfo;
import com.shuqi.model.bean.OrderInfo;
import com.shuqi.model.manager.MyAccountManager;
import com.shuqi.statistics.StatisticsEventID;
import com.shuqi.statistics.StatisticsUtils;

/**
 * 阅读页
 * 
 * @author Jianda.Yang
 * @date 2013-12-19 下午8:55:20
 * @version 1.0
 */

public class BookContentActivity extends ActivityBase implements OnClickListener,
        BookContentModelStatusListener, BookContentMenuView.OnMenuEventListener, OnSettingListener,
        OnOrderDialogListener, onViewChangeListener {

    public BookContentSettings mBookContentSettings;
    public BookContentModel mBookContentModel;
    public BookContentView mBookContentView;
    public BookContentMenuView mBookContentMenuView;
    /** 获取电量广播 */
    public BookContentBottomView mBookContentBottomView;
    /** 订单页购买按钮 */
    private ImageView mBuyButton;
    private CataLogLayout mCataLogLayout;
    /** 显示来源的底部对话框 */
    private BottomDialog mJumpFromResourceDialog = null;
    private TextView mResourceUrl = null;
    private TextView mJumpOk = null;
    private TextView mJumpCancel = null;
    private String mRealResourceUrl;
    /** 底部跳转绑定弹出框 */
    private BottomDialog mDialogBinding = null;
    /** 书包阅读完跳转搜索弹出框 */
    private BottomDialog mDialogSearch = null;
    /** 登录 */
    public static final int REQUESTCODE_LOGIN = 100;
    /** 设置是否全屏显示接收code */
    public static final int REQUESTCODE_SET_SCREEN_FULL = 1001;
    private int mSystemScreenTime = 0;
    private OrderDialog mOrderDialog;
    /** 这个变量用来标记从后台切换到前台时，是否应该显示购买对话框用 */
    private boolean isBuySuccess = false;

    /* ###############以下：在书架点击书签时，若文件不存在或删除或其他异常情况，书架要弹出相应的提示或错误对话框 */

    public static final int INTENT_REQUEST_CODE_BOOKSHLEF = 1001;
    public static final String INTENT_RESULT_BOOKSELF_BOOKNAME = "bookname";
    public static final String INTENT_RESULT_BOOKSELF_BOOKTYPE = "booktype";
    public static final String INTENT_RESULT_BOOKSELF_FILEPATH = "filepath";
    public static final String INTENT_RESULT_BOOKSELF_BOOKID = "bookid";

    /* ###############以上：在书架点击书签时，若文件不存在或删除或其他异常情况，书架要弹出相应的提示或错误对话框 */

    private static final String TAG = "BookContentActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init(savedInstanceState);
        BookCataLogDao.getInstance().registerCataLogListener(mCataLogLayout);
        System.out.println("[gaopeng812]oncreate");
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        mBookContentModel.setStartUpdateTime();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putSerializable(Constant.BOOKCONTENT_BUNDLE_KEY,
                mBookContentModel.getBookContentInfo());
        System.out.println("[gaopeng812]onsaveinstancestate");
    }

    /**
     * 初始化方法
     */
    private void init(Bundle savedInstanceState) {
        mBookContentSettings = BookContentSettings.getInstance(BookContentActivity.this);
        // 设置监听器，监听器中实现了 阅读页设置需要的一些方法
        mBookContentSettings.setOnSettingListener(this);
        mBookContentSettings.init(Util.getDensity(this));
        openHardwareAcceleration();
        hideNavigationBar();
        findViews();
        initData(savedInstanceState);
        getCatalogData();
        if (mBookContentModel.isOrderPay()) {
            btnBuyListener(true);
        }
        // showHelpImage();
    }

    /**
     * 隐藏4.0以上的 NavigationBar
     */
    private void hideNavigationBar() {
        if (Util.getOSVersion() >= 14) {
            Window window = getWindow();
            WindowManager.LayoutParams params = window.getAttributes();
            // params.systemUiVisibility = View.SYSTEM_UI_FLAG_LOW_PROFILE;
            try {
                Field f = params.getClass().getField("systemUiVisibility");
                Field f2 = View.class.getField("SYSTEM_UI_FLAG_LOW_PROFILE");
                f.setAccessible(true);
                f2.setAccessible(true);
                f.set(params, f2.getInt("SYSTEM_UI_FLAG_LOW_PROFILE"));
                // Log4an.i(TAG, "f2=" + f2.getInt("SYSTEM_UI_FLAG_LOW_PROFILE"));
            } catch (Exception e) {
                Log4an.i(TAG, e.toString());
                e.printStackTrace();
            }
        }
    }

    /**
     * 开启硬件加速
     * 
     */
    private void openHardwareAcceleration() {
        // if (Util.getOSVersion() >= 18) { // 大于4.3开启硬件加速
        // this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED,
        // WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);
        // }
    }

    private ImageView mHelpImageView;

    private boolean isShowHelpImage() {
        if (mHelpImageView.isShown()) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 显示帮助页
     */
    private void showHelpImage() {
        if (!SharedPreferenceUtil.getInstanceSharedPreferenceUtil().getBookContentHelpImageState()) {
            mBookContentModel.blockBookContentView(false);
            mHelpImageView.setVisibility(View.VISIBLE);
            mHelpImageView.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    goneHelpImage();
                }
            });
        }
    }

    /** 隐藏帮助菜单 */
    private void goneHelpImage() {
        if (mHelpImageView != null && mBookContentModel != null) {
            mHelpImageView.setVisibility(View.GONE);
            mBookContentModel.blockBookContentView(true);
            SharedPreferenceUtil.getInstanceSharedPreferenceUtil().saveBookContentHelpImageState(
                    true);
        }
    }

    /**
     * 展示购买的dialog
     */
    public void showBuyLoadingDialog() {
        // if (mBuyLoadingDialog == null) {
        // mBuyLoadingDialog = new AlertDialog.Builder(BookContentActivity.this).create();
        // mBuyLoadingDialog.setCanceledOnTouchOutside(false);
        // mBuyLoadingDialog.setOnKeyListener(new OnKeyListener() {
        // @Override
        // public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
        // hideBuyLoadingDialog();
        // finish();
        // return true;
        // }
        // });
        // }
        // if (mBuyLoadingView == null) {
        // mBuyLoadingView =
        // getLayoutInflater().inflate(R.layout.book_content_buy_dialog_view, null);
        // }
        // if (mBuyLoadingDialog != null) {
        // mBuyLoadingDialog.show();
        // mBuyLoadingDialog.setContentView(mBuyLoadingView);
        // }

        int index = PayTheme.getCurrentTheme(this);
        findViewById(R.id.time).setBackgroundColor(Constant.READ_LOAD_COLORS[index]);
        mBookContentBottomView.setLoading(mBookContentModel.mBookContentInfo.getCurChapterName(),
                "正在购买，请稍后...", mBookContentModel.mBookContentInfo.getBookname());
        mBookContentView.setViewEnabled(false);

    }

    /**
     * 隐藏购买的dialog
     */
    public void hideBuyLoadingDialog() {
        // ShuqiApplication.getApplicationHandler().post(new Runnable() {
        //
        // @Override
        // public void run() {
        // if (mBuyLoadingDialog != null) {
        // mBuyLoadingDialog.dismiss();
        // }
        // }
        // });

        findViewById(R.id.time).setBackgroundColor(0x000000);
        mBookContentBottomView.setLoading("", "", "");
        mBookContentView.setViewEnabled(true);
    }

    /**
     * 阅读页购买按钮监听
     */
    public void btnBuyListener(boolean isSet) {
        if (isSet) {
            mBuyButton.setVisibility(View.VISIBLE);
            setBtnBuyLocation();
            mBuyButton.setOnClickListener(this);
        } else {
            mBuyButton.setVisibility(View.GONE);
        }
    }

    /**
     * 设置购买按钮位置
     */
    private void setBtnBuyLocation() {
        int top =
                (mBookContentSettings.getScreenHeight() - getResources().getDimensionPixelSize(
                        R.dimen.page_pay_button_height)) / 3 * 2;
        int w = getResources().getDimensionPixelSize(R.dimen.page_pay_button_width);
        int h = getResources().getDimensionPixelSize(R.dimen.page_pay_button_height);
        RelativeLayout.LayoutParams param = new RelativeLayout.LayoutParams(w, h);
        param.addRule(RelativeLayout.CENTER_HORIZONTAL);
        param.setMargins(0, top, 0, 0);
        mBuyButton.setLayoutParams(param);
    }

    /**
     * 根据id查找view
     */
    private void findViews() {
        mBookContentBottomView = (BookContentBottomView) findViewById(R.id.time);
        mBookContentView = (BookContentView) findViewById(R.id.page_widget);
        mBookContentView.setPageTurnMode(mBookContentSettings.getmPageTurnMode());
        mBookContentView.setReadBackBg(Constant.BACK_BG_COLORS[PayTheme.getCurrentTheme()]);
        mBookContentMenuView = (BookContentMenuView) findViewById(R.id.view_menu);
        mBuyButton = (ImageView) findViewById(R.id.bookcontent_buy_btn);
        mCataLogLayout = (CataLogLayout) findViewById(R.id.act_main_left_layout);
        mHelpImageView = (ImageView) findViewById(R.id.bookcontent_help_img);
        mLoadLinearLayout = (LinearLayout) findViewById(R.id.include_loading);
    }

    /**
     * 初始化数据
     */
    private void initData(Bundle savedInstanceState) {
        BookContentInfo info;
        if (savedInstanceState != null) {
            info = (BookContentInfo) savedInstanceState
                            .getSerializable(Constant.BOOKCONTENT_BUNDLE_KEY);
        } else {
            info = (BookContentInfo) getIntent().getSerializableExtra(
                            Constant.BOOKCONTENT_BUNDLE_KEY);
        }
        if (info == null) {
            Toast.makeText(getApplicationContext(),
                    getResources().getString(R.string.bookcontent_init_fail), Toast.LENGTH_SHORT)
                    .show();
            finish();
            return;
        }

        mBookContentView.setCatalogLayout(mCataLogLayout);
        mCataLogLayout.setOnViewChangeListener(this);

        // 设置全屏
        boolean isfull =
                SharedPreferenceUtil.getInstanceSharedPreferenceUtil().getBookContentFullScreen();
        mBookContentSettings.setFullScreen(isfull);
        setFullScreen(isfull);

        // 设置阅读页字体
        mBookContentSettings
                .setTextColor(Constant.READ_FONT_COLORS[PayTheme.getCurrentTheme(this)]);// 读取保存到本地的对应主题索引值
        // 创建小说页生成类
        mBookContentBottomView.setSetting(mBookContentSettings);
        mBookContentModel = new BookContentModel(this, mBookContentView);
        mBookContentModel.setBookContentModelStatusListener(this);
        mBookContentModel.setSavedBookContentInfo(info);
        mBookContentModel.setBookContentBottomView(mBookContentBottomView);
        mBookContentMenuView.setOnMenuEventListener(this);
        mBookContentMenuView.setPageSettings(mBookContentSettings);
        mBookContentBottomView.setStatusBarHeight(mBookContentSettings.getStatusBarHeight());
        // 设置横竖屏
        setScreen();
        if (PayTheme.getCurrentTheme(this) == PayTheme.PAY_THEME) { // 如果是夜间模式
            mBookContentMenuView.setNightMenuMode();
            mBookContentSettings.setLight(mBookContentSettings.getmLight());
            mBookContentSettings.resetBuyButtonResId(Constant.ORDER_BUY_BUTTON_ID[0]);
        } else {
            mBookContentMenuView.setLightMmenuModel();
            mBookContentSettings.setLight(mBookContentSettings.getmLight());
            mBookContentSettings.resetBuyButtonResId(Constant.ORDER_BUY_BUTTON_ID[1]);
        }

        mBookContentModel.setBookContentMenuView(mBookContentMenuView);
        mBookContentModel.setCataLogLayout(mCataLogLayout);
        mBookContentModel.loadPage(true);
        // refreshBottomView();
    }

    public int getBookType() {
        return mBookContentModel.getBookType();
    }

    @Override
    public void onJumpSeekBarEnable() {
        mBookContentMenuView.IsCharpterOk();
    }

    private LinearLayout mLoadLinearLayout;

    public void showLoading(boolean isShow, boolean noEnable) {
        if (isShow) {
            int index = PayTheme.getCurrentTheme(this);
            // findViewById(R.id.time).setBackgroundColor(Constant.READ_LOAD_COLORS[index]);
            if (index == PayTheme.DEFAULT_THEME) {
                findViewById(R.id.time).setBackgroundColor(0x000000);
                if (mBookContentSettings.getVertialScreen()) {
                    findViewById(R.id.time).setBackgroundResource(R.drawable.ptheme1_background);
                } else {
                    findViewById(R.id.time).setBackgroundResource(R.drawable.ptheme1_background1);
                }
            } else {
                findViewById(R.id.time).setBackgroundDrawable(null);
                findViewById(R.id.time).setBackgroundColor(Constant.READ_LOAD_COLORS[index]);
            }
            mBookContentBottomView.setLoading(
                    mBookContentModel.mBookContentInfo.getCurChapterName(), "内容获取中，请稍候...",
                    mBookContentModel.mBookContentInfo.getBookname());
            mBookContentView.setViewEnabled(false);
            btnBuyListener(false);

            mBookContentMenuView.UnDayOrNight();
        } else {
            findViewById(R.id.time).setBackgroundDrawable(null);
            findViewById(R.id.time).setBackgroundColor(0x000000);
            mBookContentBottomView.setLoading("", "", "");
            mBookContentView.setViewEnabled(true);// !mBookContentMenuView.isMenuEnable()-->V7.3.9之前的处理方式

            mBookContentMenuView.DayOrNight(noEnable);
        }
    }

    public void openShowLoading(boolean isShow) {
        ImageView progressImageView = (ImageView) findViewById(R.id.iv_loading);
        final AnimationDrawable animationDrawable =
                (AnimationDrawable) progressImageView.getDrawable();
        if (isShow) {
            int index = PayTheme.getCurrentTheme(this);
            // mLoadLinearLayout.setBackgroundColor(Constant.READ_LOAD_COLORS[index]);
            // mLoadLinearLayout.setBackgroundResource(R.drawable.ptheme2_background);
            if (index == PayTheme.DEFAULT_THEME) {
                if (mBookContentSettings.getVertialScreen()) {
                    mLoadLinearLayout.setBackgroundResource(R.drawable.ptheme1_background);
                } else {
                    mLoadLinearLayout.setBackgroundResource(R.drawable.ptheme1_background1);
                }
            } else {
                mLoadLinearLayout.setBackgroundDrawable(null);
                mLoadLinearLayout.setBackgroundColor(Constant.READ_LOAD_COLORS[index]);
            }

            ((TextView) findViewById(R.id.tv_loading))
                    .setTextColor(Constant.READ_FONT_COLORS[index]);
            mLoadLinearLayout.setVisibility(View.VISIBLE);
            progressImageView.post(new Runnable() {
                @Override
                public void run() {
                    animationDrawable.start();
                }
            });
            mBookContentView.setViewEnabled(false);
        } else {
            mLoadLinearLayout.setVisibility(View.GONE);
            animationDrawable.stop();
            mBookContentView.setViewEnabled(true);// !mBookContentMenuView.isMenuEnable()-->V7.3.9之前的处理方式

            showHelpImage();
        }
    }

    public boolean isShowloading() {
        return mLoadLinearLayout.isShown();
    }

    /** 更换主题 */
    public void notifyUpdateTheme(int id) {
        mBookContentSettings
                .setTextColor(Constant.READ_FONT_COLORS[PayTheme.getCurrentTheme(this)]);
        mBookContentModel.notifyThemeChanged(id);
    }

    /** 设置是否全屏 */
    private void setFullScreen(boolean isfull) {
        // if (mIsFullScreen) {
        // ((Activity) mContext).getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        // } else {
        // ((Activity) mContext).getWindow()
        // .clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        // }
        if (isfull) {// 避免全屏时显示菜单黑屏
            WindowManager.LayoutParams lp = getWindow().getAttributes();
            lp.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
            getWindow().setAttributes(lp);
            // ((Activity) mContext).getWindow().addFlags(
            // WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
        } else {// 避免设置非全屏后系统栏不变黑
            WindowManager.LayoutParams attr = getWindow().getAttributes();
            attr.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
            getWindow().setAttributes(attr);
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
            if ("M040".equals(ConfigVersion.MODEL)) { // 只针对魅族2手机做特殊处理
                Util.hideNavigationBar(this);
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        settingScreenTime();
        // 设置是否是点击两侧翻页
        mBookContentModel.checkSlideTurnPageSetting();
        mBookContentModel.checkTurnMode();
        if (mBookContentMenuView.getVisibility() == View.GONE) {
            // 避免全屏模式下菜单显示时，锁屏开屏后没有了系统栏
            boolean isfull =
                    SharedPreferenceUtil.getInstanceSharedPreferenceUtil()
                            .getBookContentFullScreen();
            mBookContentSettings.setFullScreen(isfull);
            setFullScreen(isfull);
        }
        setScreen();
        mBookContentBottomView.setStatusBarHeight(mBookContentSettings.getStatusBarHeight());
        mBookContentSettings.setLineSpace(SharedPreferenceUtil.getInstanceSharedPreferenceUtil()
                .getBookContentLineSpace());
        if (mOrderDialog != null && isOrderShow && !mOrderDialog.getIsOnclickPay() && !isBuySuccess) {
            mOrderDialog.show();
        }
        System.out.println("[gaopeng812]onresume");
    }

    boolean isOrderShow;

    @Override
    protected void onPause() {
        super.onPause();
        mBookContentModel.mBookContentInfo
                .setCurChapterLineIndex(mBookContentModel.mBookContentRender.getFirstLineIndex());
        mBookContentModel.saveBookMark();
        if (mOrderDialog != null) {
            if (mOrderDialog.isShowing()) {
                isOrderShow = true;
            } else {
                isOrderShow = false;
            }
            mOrderDialog.dismiss();
        }
        recoverSystemScreenTime();
        System.out.println("[gaopeng812]onpause");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        hideBuyLoadingDialog();
        BookContentSettings.onDestroyInstance();
        mBookContentModel.destroy();
        BookCataLogDao.getInstance().unRegisterCataLogListener();
        CataLogCache.getInstance().destroy();
        // CheckTxtCatalogTool.onDestoryCheckTxtCatalogToolInstance();
        System.out.println("[gaopeng812]ondestroy");
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log4an.e("2", "requestCode=" + requestCode + ",resultCode=" + resultCode);
        if (requestCode == REQUESTCODE_LOGIN /* && resultCode == Activity.RESULT_OK && data != null */) {
            // mBookContentModel.doLogin();
            btnBuyListener(true);
            onOrderDialogDismiss();
        } else if (requestCode == REQUESTCODE_SET_SCREEN_FULL) {
            setStatusBarHeight(SharedPreferenceUtil.getInstanceSharedPreferenceUtil()
                    .getBookContentFullScreen());
            mBookContentBottomView.setStatusBarHeight(getStatusBarHeight());
            mBookContentModel.mBookContentRender.setNotifyChangeSetting(true);
            mBookContentModel.notifyUpdateDataChanged(false);
            mBookContentModel.mBookContentRender.setNotifyChangeSetting(false);
            // setBtnBuyLocation();
        } else { // 目前是充值成功返回 需要加判断 目前没执行该方法
            if (requestCode == Constant.ORDER_REQUESTCOD && resultCode == Activity.RESULT_OK) {
                UserInfo userInfo = MyAccountManager.getInstance(this, true);
                if (!MyAccountManager.isVipUser(userInfo)
                        && !MyAccountManager.isGuestUser(userInfo)) {
                    showBottomDialog();
                }
            }

        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (event.getRepeatCount() != 0)
            return true;
        if (mBookContentSettings.isCopyMode()) {
            mBookContentModel.onViewCopyModeCompleted();
            return false;
        }
        switch (keyCode) {
            case KeyEvent.KEYCODE_VOLUME_UP:
                if (!SharedPreferenceUtil.getInstanceSharedPreferenceUtil()
                        .getBookContentVolumeEnabled())
                    return false;
                if (mBookContentView.getViewEnabled() && !isShowHelpImage()
                        && mBookContentMenuView.getVisibility() == View.GONE) {
                    mBookContentModel.turnPrevPage();
                    mBookContentModel.blockBookContentView(true);
                    return true;
                }
                break;
            case KeyEvent.KEYCODE_VOLUME_DOWN:
                if (!SharedPreferenceUtil.getInstanceSharedPreferenceUtil()
                        .getBookContentVolumeEnabled())
                    return false;
                if (mBookContentView.getViewEnabled() && !isShowHelpImage()
                        && mBookContentMenuView.getVisibility() == View.GONE) {
                    mBookContentModel.turnNextPage();
                    mBookContentModel.blockBookContentView(true);
                    return true;
                }
                break;
            case KeyEvent.KEYCODE_MENU: {
                if (mHelpImageView != null && mHelpImageView.isShown()) {
                    goneHelpImage();
                    return true;
                }
                if (mCataLogLayout.mLeftSliderLayout.isOpen()) {
                    return true;
                }
                if (isShowloading()) {
                    return true;
                }
                mBookContentModel.onMenuKeyDown();
                return true;
            }
            case KeyEvent.KEYCODE_BACK: {
                if (mHelpImageView != null && mHelpImageView.isShown()) {
                    goneHelpImage();
                    return true;
                }
                if (mBookContentModel.onBackKeyDown()) {
                    return true;
                }
                break;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 复写音量上下键，去除音量调节的声音
     */
    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (event.getRepeatCount() != 0)
            return true;
        switch (keyCode) {
            case KeyEvent.KEYCODE_VOLUME_UP:
                if (SharedPreferenceUtil.getInstanceSharedPreferenceUtil()
                        .getBookContentVolumeEnabled())
                    return true;
            case KeyEvent.KEYCODE_VOLUME_DOWN:
                if (SharedPreferenceUtil.getInstanceSharedPreferenceUtil()
                        .getBookContentVolumeEnabled()) {
                    return true;
                }
        }
        return super.onKeyUp(keyCode, event);
    }

    /** 跳到来源的底部对话框 */
    public void showJumpFromResourceDialog() {
        View view = View.inflate(BookContentActivity.this, R.layout.view_jump_from_resource, null);
        if (mBookContentSettings.isNightMode()) {
            if (mBookContentSettings.getVertialScreen()) {
                view =
                        View.inflate(BookContentActivity.this,
                                R.layout.view_jump_from_resource_night, null);
            } else {
                view =
                        View.inflate(BookContentActivity.this,
                                R.layout.view_jump_from_resource_horrizion_night, null);
            }
        } else {
            if (mBookContentSettings.getVertialScreen()) {
                view =
                        View.inflate(BookContentActivity.this, R.layout.view_jump_from_resource,
                                null);
            } else {
                view =
                        View.inflate(BookContentActivity.this,
                                R.layout.view_jump_from_resource_horrizion, null);
            }
        }
        mJumpFromResourceDialog = new BottomDialog(BookContentActivity.this, view);
        initJumpFromResourceDialog(view);
        ShuqiApplication.getApplicationHandler().postDelayed(new Runnable() {
            public void run() {
                mJumpFromResourceDialog.show();
            }
        }, 600);
    }

    private void initJumpFromResourceDialog(View view) {
        mResourceUrl = (TextView) view.findViewById(R.id.url);
        mJumpOk = (TextView) view.findViewById(R.id.ok_tv);
        mJumpCancel = (TextView) view.findViewById(R.id.cancel_tv);

        mResourceUrl.setText(mRealResourceUrl);
        mJumpOk.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                StatisticsUtils.onEvent(BookContentActivity.this,
                        StatisticsEventID.BOOKCONTENT_SHENMA_EXIT);
                WebKitActivity.openWebkit(BookContentActivity.this, mRealResourceUrl);
                mJumpFromResourceDialog.dismiss();
            }
        });
        mJumpCancel.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mJumpFromResourceDialog.dismiss();
            }
        });
    }

    @Override
    public void activityLogicForward() {}

    @Override
    public void activityInitData() {}

    private static final int SYSTEM_TIME = -2;

    /**
     * 设置锁屏时间 时间为mBookContentSettings.getKeepScreenTime()
     */
    private void settingScreenTime() {
        try {
            mSystemScreenTime =
                    Settings.System
                            .getInt(getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT);
            int keepTime = mBookContentSettings.getKeepScreenTime();
            Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT,
                    (keepTime == SYSTEM_TIME ? mSystemScreenTime : keepTime));
        } catch (SettingNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 将锁屏时间回复为默认时间
     */
    private void recoverSystemScreenTime() {
        if (mSystemScreenTime != 0) {
            Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT,
                    mSystemScreenTime);
        }
    }

    /** 显示底部弹出框 */
    private void showBottomDialog() {
        if (this.mDialogBinding == null) {
            View v = View.inflate(this, R.layout.account_safety_tips, null);
            this.mDialogBinding = new BottomDialog(this, v);
            this.initDialogBindingDialog(v);
            v.setOnClickListener(this);
        }
        this.mDialogBinding.show();
        StatisticsUtils.onEvent(StatisticsEventID.AFTERPAYFINISH_HINT_SHOWBIND);
    }

    /**
     * 事件响应
     */
    private void initDialogBindingDialog(View view) {
        view.findViewById(R.id.binding_account).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                AccountBindActivity.show(BookContentActivity.this);
                if (mDialogBinding != null) {
                    mDialogBinding.dismiss();
                }
                StatisticsUtils.onEvent(StatisticsEventID.AFTERPAYFINISH_HINT_CLICKBIND);
            }
        });
    }

    /**
     * 自动购买
     */
    public void onAutoBuy() {
        runOnUiThread(new Runnable() {
            public void run() {
                mBookContentModel.blockBookContentView(true);
                btnBuyListener(false);
                showLoading(true, false);
                showBuyLoadingDialog();
            };
        });
    }

    public void returnFinish() {
        if (isFinishing()) {
            return;
        }
    }

    public void showBuySuccessful(boolean isShowDialog) {
        isBuySuccess = true;
        if (mOrderDialog != null) {
            returnFinish();
            mOrderDialog.showBuySuccessful(isShowDialog);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bookcontent_buy_btn:// 点击购买的按钮
                // 移除title，设置为全屏
                final BookContentInfo bookContentInfo = mBookContentModel.getBookContentInfo();
                if (BookContentUtils.TYPE_NO_LOGIN.equals(bookContentInfo.getCurChapterType())) {
                    LoginActivity.openLoginForResult(this, BookContentActivity.REQUESTCODE_LOGIN);
                } else {
                    if (mBookContentModel.getIndexBtnTexts() == BookContentRender.BOOK_CONTENT_BUTTON_TEXT_COVER) {
                        BookCoverActivity.openBookCoverClearTop(this, bookContentInfo.getBookId());
                        StatisticsUtils.onEvent(this,
                                StatisticsEventID.BOOKCONTENT_CLICK_GOCOVER_DOWN);
                        finish();
                    } else if (mBookContentModel.getIndexBtnTexts() == BookContentRender.BOOK_CONTENT_BUTTON_TEXT_RETRY) {
                        if (!Util.isNetworkConnected(this)) {
                            Log4an.i(
                                    "yjd",
                                    "【重试】" + "name="
                                            + mBookContentModel.mBookContentInfo.getBookname()
                                            + ",bid="
                                            + mBookContentModel.mBookContentInfo.getBookId()
                                            + ",cid="
                                            + mBookContentModel.mBookContentInfo.getCurChapterCid()
                                            + ",uid=" + mBookContentModel.mBookContentInfo.getUid()
                                            + ",isNeedBuy="
                                            + mBookContentModel.mBookContentInfo.isNeedBuy());
                            Toast.makeText(this, "网络不给力，请重试", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        mBookContentModel.reloadCurChapter();
                    } else {
                        if (mOrderDialog != null && mOrderDialog.isShowing()) {
                            return;
                        }
                        // 修改华为8860连续点击购买按钮出现crash问题
                        if (mBuyButton != null) {
                            mBuyButton.setEnabled(false);
                        }
                        if (MyAccountManager.isAvailableUser(this)) {
                            showOrderDialog(bookContentInfo);
                        } else {
                            LoginActivity.openLoginForResult(this,
                                    BookContentActivity.REQUESTCODE_LOGIN);
                        }

                        // CheckUser.checkUserStateBeforeJump(this, new CheckUserListener() {
                        // @Override
                        // public void onPassed() {
                        // showOrderDialog(bookContentInfo);
                        // }
                        // });
                    }
                }
                break;
        }
    }

    /**
     * 显示购买对话框
     * 
     * @param bookContentInfo
     */
    private void showOrderDialog(BookContentInfo bookContentInfo) {
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setBookId(bookContentInfo.getBookId());
        orderInfo.setChapterId(bookContentInfo.getCurChapterCid());
        orderInfo.setBookName(bookContentInfo.getBookname());

        // 修改Integer.parseInt可能会抛溢出导致crash的bug
        int payMode = 2;
        try {
            payMode =
                    TextUtils.isEmpty(bookContentInfo.getCurChapterPayMode()) ? 2 : Integer
                            .parseInt(bookContentInfo.getCurChapterPayMode());
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }

        orderInfo.setPayMode(payMode);
        orderInfo.setPrice(bookContentInfo.getCurChapterPrice());
        if (orderInfo.getPayMode() == 2) {
            orderInfo.setOrderDetail(bookContentInfo.getCurChapterName());
            StatisticsUtils.onEvent(StatisticsEventID.BOOKCONTENT_BUY_CHAPTER);
        } else if (orderInfo.getPayMode() == 3) {
            orderInfo.setOrderDetail("全本");
            StatisticsUtils.onEvent(StatisticsEventID.BOOKCONTENT_BUY_BOOK);
        } else {
            orderInfo.setOrderDetail(orderInfo.getBookName());
        }

        // 开始购买，设置购买未成功，当购买成功时，会置true；
        // 这个变量用来标记从后台切换到前台时，是否应该显示购买对话框用
        isBuySuccess = false;

        mOrderDialog =
                new OrderDialog(this, orderInfo, mBookContentSettings.isNightMode(),
                        mBookContentSettings.getVertialScreen());
        mOrderDialog.setmOnOrderDialogListener(this);
        mOrderDialog.show();
    }

    @Override
    public void onLoadingStatusChanged(final boolean isLoading, final boolean noEnable) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                showLoading(isLoading, noEnable);
                if (isLoading) {
                    mBookContentMenuView.setJumpSeekBarDisable();
                } else {
                    mBookContentMenuView.setJumpSeekBarEnable();
                }
            }
        });
    }

    @Override
    public void onOpenLoadingStatusChanged(final boolean isLoading) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                openShowLoading(isLoading);
                if (isLoading) {
                    mBookContentMenuView.setJumpSeekBarDisable();
                } else {
                    mBookContentMenuView.setJumpSeekBarEnable();
                }
            }
        });
    }

    @Override
    public void onShowMsg(int resId) {
        ToastUtil.showToastFullyCustomizable(this, getString(resId));
    }

    @Override
    public void onReadBagEnd(String BookId, final String bookName) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (mDialogSearch == null) {
                    View v =
                            View.inflate(BookContentActivity.this, R.layout.view_dialog_common,
                                    null);
                    ((TextView) v.findViewById(R.id.dialog_common_title)).setText("阅读提示");
                    ((TextView) v.findViewById(R.id.dialog_common_tips))
                            .setText("本地书包已读完，你可以去搜索缓存全本。");
                    ((Button) v.findViewById(R.id.dialog_common_confirm)).setText("搜索全本");

                    mDialogSearch = new BottomDialog(BookContentActivity.this, v);
                    OnClickListener listener = new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (v.getId() == R.id.dialog_common_cancel) {
                                mDialogSearch.dismiss();
                            } else if (v.getId() == R.id.dialog_common_confirm) {
                                mDialogSearch.dismiss();
                                BookSearchResultActivity.open(BookContentActivity.this, bookName);
                            }
                        }
                    };
                    v.findViewById(R.id.dialog_common_cancel).setOnClickListener(listener);
                    v.findViewById(R.id.dialog_common_confirm).setOnClickListener(listener);
                }
                mDialogSearch.show();
            }
        });
    }

    @Override
    public void onNeedBuyStatusChanged(final boolean isNeedBuy) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                btnBuyListener(isNeedBuy);
            }
        });
    }

    @Override
    public void onBuySuccessed(final boolean isShowDialog) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                returnFinish();
                showBuySuccessful(isShowDialog);
            }
        });

    }

    @Override
    public void onBuyLoadingStatusChanged(final boolean isShow) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (isShow) {
                    showBuyLoadingDialog();
                } else {
                    hideBuyLoadingDialog();
                }
            }
        });
    }

    @Override
    public void onLoadFailed(BookContentInfo bookContentInfo) {

        if (bookContentInfo != null) {
            setResult(Activity.RESULT_OK, buildErrorIntent(bookContentInfo));
        } else {
            setResult(Activity.RESULT_CANCELED);
        }
        finish();
    }

    private Intent buildErrorIntent(BookContentInfo bookContentInfo) {
        Intent intent = new Intent();
        intent.putExtra(INTENT_RESULT_BOOKSELF_BOOKTYPE, bookContentInfo.getType());
        intent.putExtra(INTENT_RESULT_BOOKSELF_BOOKNAME, bookContentInfo.getBookname());
        intent.putExtra(INTENT_RESULT_BOOKSELF_FILEPATH, bookContentInfo.getFliePath());
        intent.putExtra(INTENT_RESULT_BOOKSELF_BOOKID, bookContentInfo.getBookId());
        return intent;
    }

    @Override
    public void onShowOrigin(String origin) {
        origin = TextUtils.isEmpty(origin) ? "" : "来源:" + origin;
        ((TextView) findViewById(R.id.tv_menutop_chaptersrc_url)).setText(origin);
    }

    @Override
    public void onPostTaskToUiThread(Runnable task) {
        runOnUiThread(task);
    }

    @Override
    public void onCloseMenu(boolean isAnimation) {
        mBookContentModel.blockBookContentView(true);
    }

    @Override
    public float onShowJumpSeekBar() {
        return mBookContentModel.getReadedProgress();
    }

    @Override
    public void onJumpSeeked(float progress) {
        mBookContentModel.doJumpSeeked(progress);
    }

    @Override
    public void refreshBottomView() {
        // mBookContentModel.loadCurPage();
        // mBookContentModel.notifyUpdateDataChanged();
        // mBookContentModel.notifyUpdateContentChanged();
        // mBookContentModel.loadBookContentInfoCompleted();
        mBookContentModel.notifyChangeScreen();
        onNotifyUpdateSettingsChanged();
        mBookContentBottomView.refresh();
        mBookContentView.postInvalidateRefresh();
        mBookContentModel.renderNewContentPage(false);
        if (mBuyButton != null && mBuyButton.isShown()) {
            setBtnBuyLocation();
        }

    }

    @Override
    public void showChapterName(float progress) {
        if (mBookContentMenuView.isProgressShow()) {
            mBookContentModel.showCharpterName(progress);
        }
    }

    @Override
    public boolean hasPreChapter() {
        return mBookContentModel.hasPreChapter();
    }

    @Override
    public boolean hasNextChapter() {
        return mBookContentModel.hasNextChapter();
    }

    @Override
    public void changeScreen() {
        boolean screenOrientation_portrait = mBookContentSettings.getVertialScreen();
        screenOrientation_portrait = !screenOrientation_portrait;
        SharedPreferenceUtil.getInstanceSharedPreferenceUtil().saveBookContentPortraitScreen(
                screenOrientation_portrait);
        if (screenOrientation_portrait) {
            mBookContentSettings.setVertialScreen(true);
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        } else {
            mBookContentSettings.setVertialScreen(false);
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        }
    }

    /** 改变横竖屏及菜单 */
    private void setScreen() {
        boolean screenOrientation_portrait = mBookContentSettings.getVertialScreen();
        if (screenOrientation_portrait) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            mBookContentMenuView.setScreenVertical();

        } else {
            mBookContentMenuView.setScreenHorizontal();
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        }

    }

    @Override
    public void onJumpPrevChapter() {
        mBookContentModel.doJumpPrevChapter();
    }

    @Override
    public void onJumpNextChapter() {
        mBookContentModel.doJumpNextChapter();
    }

    @Override
    public void onNavigateToCatalog() {
        ShuqiApplication.getApplicationHandler().postDelayed(new Runnable() {
            public void run() {
                mBookContentModel.doNavigateToCatalog();
            }
        }, 250);
    }

    @Override
    public void onNavigateToCover() {
        String url =
                Urls.getWebBookCoverUrl(mBookContentModel.getBookContentInfo().getBookId(),
                        mBookContentModel.getBookContentInfo().getSourceId(), this);
        WebKitActivity.openWebkit(BookContentActivity.this, url);
    }

    @Override
    public void onNavigateToShelf() {
        BookShelfActivity.show(this, true);
        StatisticsUtils.onEvent(StatisticsEventID.BOOKCONTENT_MENU_BACK);
    }

    @Override
    public void onNavigateToBack() {
        finish();
        StatisticsUtils.onEvent(StatisticsEventID.BOOKCONTENT_MENU_SHELF);
    }

    @Override
    public void onNavigateToSourceWeb() {
        String url = ((TextView) findViewById(R.id.tv_menutop_chaptersrc_url)).getText().toString();
        int index = url.indexOf(":") + 1;
        mRealResourceUrl = url.substring(index);
        showJumpFromResourceDialog();
    }

    @Override
    public int onScreenLight() {
        return mBookContentSettings.getmLight();
    }

    @Override
    public boolean isBookContentEnabled() {
        return mBookContentModel.isBookContentEnabled();
    }

    @Override
    public View onGetView() {
        return mBookContentView;
    }

    @Override
    public int getBarHeight() {
        // return mBookContentView.getBarHeight();
        return Util.getStatusBarHeight();
    }

    @Override
    public void onNotifyUpdateSettingsChanged() {
        mBookContentModel.notifyUpdateSettingsChanged();
    }

    @Override
    public void onNotifyUpdateTheme(int id) {
        notifyUpdateTheme(id);
    }

    @Override
    public int getReadState() {
        return mBookContentModel.mReadState;
    }

    @Override
    public int getCurReadState() {
        return mBookContentModel.mReadState;
    }

    @Override
    public void onSetLight(int mLight) {
        WindowManager.LayoutParams lp = this.getWindow().getAttributes();

        if (SharedPreferenceUtil.getInstanceSharedPreferenceUtil().getBookContentSystemButton()) {
            lp.screenBrightness = -1;
        } else {
            if (mLight == 0) {// 系统默认是0，第一次初始化时会黑屏
                lp.screenBrightness = -1;
            } else {
                lp.screenBrightness = mLight * 1.0f / 100;
            }
        }
        SharedPreferenceUtil.getInstanceSharedPreferenceUtil().saveBookContentScreenLight(mLight);

        this.getWindow().setAttributes(lp);

    }

    @Override
    public void onSetSystemLight() {
        boolean isSystemLight =
                SharedPreferenceUtil.getInstanceSharedPreferenceUtil().getBookContentSystemButton();
        isSystemLight = !isSystemLight;
        SharedPreferenceUtil.getInstanceSharedPreferenceUtil().saveBookContentSystemButton(
                isSystemLight);

        WindowManager.LayoutParams lp = this.getWindow().getAttributes();
        if (isSystemLight) {
            lp.screenBrightness = -1;
        } else {
            int light =
                    SharedPreferenceUtil.getInstanceSharedPreferenceUtil().getBookContentLight();
            if (light == 0) {
                lp.screenBrightness = -1;
            } else {
                lp.screenBrightness = light * 1.0f / 100;
            }
        }
        this.getWindow().setAttributes(lp);

    }

    @Override
    public void refreshPage(ChapterInfo bookInfo, boolean isShowDialog) {
        mBookContentModel.refreshPage(bookInfo, isShowDialog);
    }

    @Override
    public void refreshDownView() {
        mBookContentModel.refreshDownView();
    }

    @Override
    public void onOrderDialogDismiss() {
        // 修改华为8860连续点击购买按钮出现crash问题
        if (mBuyButton != null) {
            mBuyButton.setEnabled(true);
        }
    }

    @Override
    public void onSetBookContentEnabled(boolean isEnable) {
        mBookContentModel.blockBookContentView(isEnable);
    }

    @Override
    public boolean isLoading() {
        return mBookContentModel.isLoading();
    }

    @Override
    public String onTxtFilePath() {
        return mBookContentModel.getTxtFilePath();
    }

    @Override
    public void onOpenWebkit(String url) {
        WebKitActivity.openWebkit(BookContentActivity.this, url);
    }

    /** 为了解决umd和epub文件点击菜单后点击上一章或下一章无目录数据的提示 */
    private void getCatalogData() {
        if (mBookContentModel.mBookContentInfo.getType() == Constant.BOOKTYPE_EPUB
                || mBookContentModel.mBookContentInfo.getType() == Constant.BOOKTYPE_UMD)
            ShuqiApplication.getApplicationHandler().postDelayed(new Runnable() {
                public void run() {
                    mBookContentModel.doOnlyGetCatalogData();
                }
            }, 250);
    }

    @Override
    public void onReturnFinish() {
        returnFinish();
    }

    @Override
    public int onScreenVisibleLineNum() {
        return mBookContentSettings.getScreenVisibleLineNum();
    }

    @Override
    public int onViewDistanceInScrollMode() {
        return (mBookContentSettings.getTextSize() + (int) mBookContentSettings.getLineSpace())
                * mBookContentModel.mBookContentInfo.getCurSreenLineCount()
                + (int) mBookContentModel.mBookContentRender.mScrollOffset;
    }

    @Override
    public void onJumpSeekBarDisable() {
        // TODO Auto-generated method stub

    }

    /*
     * (non-Javadoc)
     * 
     * @see
     * com.shuqi.model.BookContentModel.BookContentModelStatusListener#setStatusBarHeight(boolean)
     */
    @Override
    public void setStatusBarHeight(boolean isSetStatusBarHeight) {
        if (isSetStatusBarHeight) {
            mBookContentSettings.setmStatusBarHeight(0);
        } else {
            mBookContentSettings.setmStatusBarHeight(Util.getStatusBarHeight());
        }
    }

    /*
     * (non-Javadoc)
     * 
     * @see com.shuqi.model.BookContentModel.BookContentModelStatusListener#getStatusBarHeight()
     */
    @Override
    public int getStatusBarHeight() {
        return mBookContentSettings.getStatusBarHeight();
    }

}
